<template>
  <div class="chat-container">
    <div class="chat-sidebar">
      <div class="chat-header">
        <h2>消息列表</h2>
        <a-button type="primary" shape="circle">
          <icon-plus />
        </a-button>
      </div>
      <div class="chat-list">
        <div 
          v-for="(chat, index) in chatList" 
          :key="index" 
          class="chat-item" 
          :class="{ active: currentChat.id === chat.id }"
          @click="selectChat(chat)"
        >
          <a-avatar :size="40" :image-url="chat.avatar">{{ chat.name.charAt(0) }}</a-avatar>
          <div class="chat-info">
            <div class="chat-name">{{ chat.name }}</div>
            <div class="chat-preview">{{ chat.lastMessage }}</div>
          </div>
          <div class="chat-meta">
            <div class="chat-time">{{ chat.time }}</div>
            <a-badge v-if="chat.unread" :count="chat.unread" />
          </div>
        </div>
      </div>
    </div>
    
    <div class="chat-main">
      <div class="chat-header">
        <div class="chat-title">
          <h2>{{ currentChat.name }}</h2>
          <div class="chat-status" :class="{ online: currentChat.online }">
            {{ currentChat.online ? '在线' : '离线' }}
          </div>
        </div>
        <div class="chat-actions">
          <a-button shape="circle">
            <icon-search />
          </a-button>
          <a-button shape="circle">
            <icon-more-vertical />
          </a-button>
        </div>
      </div>
      
      <div class="chat-messages" ref="messagesContainer">
        <div 
          v-for="(message, index) in messages" 
          :key="index" 
          class="message-item"
          :class="{ 'message-self': message.isSelf }"
        >
          <div class="message-avatar" v-if="!message.isSelf">
            <a-avatar :size="36" :image-url="currentChat.avatar">
              {{ currentChat.name.charAt(0) }}
            </a-avatar>
          </div>
          <div class="message-content">
            <div class="message-bubble">
              {{ message.content }}
            </div>
            <div class="message-time">{{ message.time }}</div>
          </div>
          <div class="message-avatar" v-if="message.isSelf">
            <a-avatar :size="36" :image-url="userAvatar">
              {{ userName.charAt(0) }}
            </a-avatar>
          </div>
        </div>
      </div>
      
      <div class="chat-input">
        <div class="input-toolbar">
          <a-button shape="circle">
            <icon-emoji />
          </a-button>
          <a-button shape="circle">
            <icon-image />
          </a-button>
          <a-button shape="circle">
            <icon-file />
          </a-button>
        </div>
        <div class="input-area">
          <a-textarea 
            v-model="messageInput" 
            :auto-size="{ minRows: 1, maxRows: 4 }" 
            placeholder="输入消息..." 
            @keydown.enter.prevent="sendMessage"
          />
        </div>
        <div class="input-actions">
          <a-button type="primary" @click="sendMessage">
            发送
          </a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue';
import { useRoute } from 'vue-router';

const route = useRoute();
const messagesContainer = ref(null);
const messageInput = ref('');
const userAvatar = ref('');
const userName = ref('当前用户');

// 模拟数据
const chatList = ref([
  {
    id: 1,
    name: '张老师',
    avatar: '',
    lastMessage: '同学们，今天的作业已经布置在系统中，请及时完成。',
    time: '10:30',
    unread: 0,
    online: true
  },
  {
    id: 2,
    name: '李同学',
    avatar: '',
    lastMessage: '请问这道题该怎么解答？我有点不明白...',
    time: '昨天',
    unread: 0,
    online: false
  },
  {
    id: 3,
    name: '王助教',
    avatar: '',
    lastMessage: '下周一将进行期中测验，请大家做好准备。',
    time: '2天前',
    unread: 0,
    online: true
  }
]);

const currentChat = ref(chatList.value[0]);

// 根据路由参数选择当前聊天
onMounted(() => {
  const chatId = parseInt(route.params.id);
  const foundChat = chatList.value.find(chat => chat.id === chatId);
  if (foundChat) {
    currentChat.value = foundChat;
    // 标记为已读
    foundChat.unread = 0;
  }
  scrollToBottom();
});

// 模拟消息数据
const messages = ref([
  {
    content: '你好，有什么问题需要帮助吗？',
    time: '10:00',
    isSelf: false
  },
  {
    content: '我想请教一下关于下周考试的范围',
    time: '10:02',
    isSelf: true
  },
  {
    content: '考试范围包括第一章到第五章的所有内容，重点是第三章和第四章。',
    time: '10:05',
    isSelf: false
  },
  {
    content: '好的，谢谢老师！我会认真复习的。',
    time: '10:06',
    isSelf: true
  },
  {
    content: '有任何问题随时可以问我。',
    time: '10:08',
    isSelf: false
  }
]);

// 选择聊天
const selectChat = (chat) => {
  currentChat.value = chat;
  // 标记为已读
  chat.unread = 0;
  scrollToBottom();
};

// 发送消息
const sendMessage = () => {
  if (!messageInput.value.trim()) return;
  
  // 添加新消息
  messages.value.push({
    content: messageInput.value,
    time: formatTime(new Date()),
    isSelf: true
  });
  
  // 清空输入框
  messageInput.value = '';
  
  // 滚动到底部
  nextTick(() => {
    scrollToBottom();
  });
  
  // 模拟回复
  setTimeout(() => {
    messages.value.push({
      content: '收到你的消息，稍后回复。',
      time: formatTime(new Date()),
      isSelf: false
    });
    
    nextTick(() => {
      scrollToBottom();
    });
  }, 1000);
};

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

// 格式化时间
const formatTime = (date) => {
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
};

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  nextTick(() => {
    scrollToBottom();
  });
});
</script>

<style scoped lang="less">
.chat-container {
  display: flex;
  height: calc(100vh - 120px);
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  margin: 20px auto;
  max-width: 1200px;
}

.chat-sidebar {
  width: 300px;
  border-right: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
  
  .chat-header {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f0f0f0;
    
    h2 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }
  }
  
  .chat-list {
    flex: 1;
    overflow-y: auto;
    
    .chat-item {
      display: flex;
      padding: 12px 16px;
      cursor: pointer;
      transition: all 0.3s;
      
      &:hover, &.active {
        background-color: #f5f5f5;
      }
      
      &.active {
        border-left: 3px solid #1890ff;
      }
      
      .chat-info {
        flex: 1;
        margin: 0 12px;
        overflow: hidden;
        
        .chat-name {
          font-weight: 500;
          margin-bottom: 4px;
        }
        
        .chat-preview {
          font-size: 12px;
          color: #999;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
      
      .chat-meta {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        
        .chat-time {
          font-size: 12px;
          color: #999;
          margin-bottom: 4px;
        }
      }
    }
  }
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  
  .chat-header {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f0f0f0;
    
    .chat-title {
      display: flex;
      align-items: center;
      
      h2 {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        margin-right: 8px;
      }
      
      .chat-status {
        font-size: 12px;
        color: #999;
        
        &.online {
          color: #52c41a;
        }
      }
    }
    
    .chat-actions {
      display: flex;
      gap: 8px;
    }
  }
  
  .chat-messages {
    flex: 1;
    padding: 16px;
    overflow-y: auto;
    background-color: #f9f9f9;
    
    .message-item {
      display: flex;
      margin-bottom: 16px;
      
      &.message-self {
        flex-direction: row-reverse;
        
        .message-content {
          align-items: flex-end;
          
          .message-bubble {
            background-color: #1890ff;
            color: #fff;
            border-radius: 16px 4px 16px 16px;
          }
        }
      }
      
      .message-avatar {
        margin: 0 8px;
      }
      
      .message-content {
        display: flex;
        flex-direction: column;
        max-width: 70%;
        
        .message-bubble {
          padding: 12px 16px;
          background-color: #fff;
          border-radius: 4px 16px 16px 16px;
          box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
          margin-bottom: 4px;
          word-break: break-word;
        }
        
        .message-time {
          font-size: 12px;
          color: #999;
        }
      }
    }
  }
  
  .chat-input {
    padding: 16px;
    border-top: 1px solid #f0f0f0;
    
    .input-toolbar {
      display: flex;
      gap: 8px;
      margin-bottom: 8px;
    }
    
    .input-area {
      margin-bottom: 8px;
    }
    
    .input-actions {
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>